package Maps 
{
	import com.junkbyte.console.Cc;
	import Editor.RegionsEditor;
	import flash.display.LoaderInfo;
	import flash.display.Sprite;	
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.external.ExternalInterface;
	import Utils.TextUtils;
	/**
	 * ...
	 * @author Serg de Adelantado
	 */
	public class Viewer extends Sprite 
	{	
		private var FLoader:MapLoader;
		private var FParser:MapParser;
		private var FEditor:RegionsEditor;
		private var FTooltip:Tooltip;
		
		public function Viewer() 
		{
			Cc.startOnStage(this, '`');
			addEventListener(Event.ADDED_TO_STAGE, OnAddedToStage);		
			FLoader = new MapLoader();
			FParser = FLoader.Parser;
			addChild(FLoader);
			FLoader.addEventListener(Event.COMPLETE, OnLoadingComplete);
			var vPath:String = Path;
			if(vPath && vPath != 'null')
				FLoader.Load(vPath);
			else
				FLoader.PrintSettingsError();
			FEditor = new RegionsEditor();
			FTooltip = new Tooltip();			
		}	
		
		private function get Path():String
		{		
			var vResult:String = null;
			vResult = LoaderInfo(root.loaderInfo).parameters['settings'];
			if (vResult && vResult.length > 1)
			{
				Cc.logch('XML File', 'From FlashVars: ' + vResult);
				return vResult;
			}
			else
			{
				var vUrl:String = String(ExternalInterface.call("function(){return document.location.href.toString();}"));
				if (vUrl && vUrl.length > 1)
				{
					var vEnd:int = vUrl.lastIndexOf('/');
					if(vEnd > 0)
						vUrl = vUrl.substring(0, vEnd + 1) + 'settings.xml';
					Cc.logch('XML File', 'From current URL: ' + vUrl);
					vResult = vUrl;
				}
			}
			return vResult;
		}
		
		private function OnAddedToStage(e:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, OnAddedToStage);
			ApplyStageMode();
		}		
		
		private function OnLoadingComplete(e:Event):void 
		{
			FLoader.visible = false;
			addChild(FLoader.Image);			
			for (var i in FParser.Regions)
			{
				addChild(FParser.Regions[i]);
				FParser.Regions[i].addEventListener(MouseEvent.MOUSE_OVER, OnRegionMouseOver);
				FParser.Regions[i].addEventListener(MouseEvent.MOUSE_OUT, OnRegionMouseOut);
			}
			//addChild(FEditor);
			addChild(FTooltip);
		}		
		
		private function OnRegionMouseOver(e:MouseEvent):void 
		{
			FTooltip.visible = true;
			FTooltip.Region = MapRegion(e.target);
		}
		
		private function OnRegionMouseOut(e:MouseEvent):void 
		{
			FTooltip.visible = false;
		}
		
		private function ApplyStageMode(AScale:String = StageScaleMode.NO_SCALE, AAlign:String = StageAlign.TOP_LEFT):void
		{
			stage.scaleMode = AScale;
			stage.align = AAlign;
		}
	}
}